<template>
	<view class="container">
    <CustomNavBar title="余额变动明细" />

		<!-- <view class="header">
			<view class="back-btn" @click="goBack">返回</view>
			<view class="title">余额明细</view>
			<view class="placeholder"></view>
		</view> -->
		
		<view class="tabs">
			<view 
				class="tab-item" 
				:class="{ active: activeTab === 0 }" 
				@click="handleTabChange(0)"
			>
				全部
				<view class="tab-line" v-if="activeTab === 0"></view>
			</view>
			<view 
				class="tab-item" 
				:class="{ active: activeTab === 1 }" 
				@click="handleTabChange(1)"
			>
				支出
				<view class="tab-line" v-if="activeTab === 1"></view>
			</view>
			<view 
				class="tab-item" 
				:class="{ active: activeTab === 2 }" 
				@click="handleTabChange(2)"
			>
				收入
				<view class="tab-line" v-if="activeTab === 2"></view>
			</view>
		</view>
		
		<view class="transaction-list">
			<view class="month-group" v-for="(group, index) in filteredTransactions" :key="index">
				<view class="month-header">{{ group.month }}</view>
				
				<view class="transaction-item" v-for="(item, idx) in group.items" :key="idx">
					<view class="transaction-left">
						<view class="transaction-type-icon" :class="item.type">
							{{ item.typeIcon }}
						</view>
						<view class="transaction-info">
							<view class="transaction-title">{{ item.title }}</view>
							<view class="transaction-time">{{ item.time }}</view>
						</view>
					</view>
					<view class="transaction-amount" :class="{ 'income': item.isIncome }">
						{{ item.isIncome ? '+' : '-' }}{{ item.amount }}元
					</view>
				</view>
			</view>
			
			<!-- 加载状态提示 -->
			<view class="loading-tip" v-if="loading">
				<text>加载中...</text>
			</view>
			<view class="loading-tip" v-else-if="!hasMore && transactions.length > 0">
				<text>没有更多数据了</text>
			</view>
			<view class="loading-tip" v-else-if="transactions.length === 0">
				<text>暂无交易记录</text>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getWalletPage } from '@/api/app/withdraw.js';
import { onReachBottom } from '@dcloudio/uni-app'
import CustomNavBar from '@/components/CustomNavBar.vue'

const activeTab = ref(0); // 0: 全部, 1: 支出, 2: 收入
const transactions = ref([]);
const currentPage = ref(1);
const hasMore = ref(true);
const loading = ref(false);

// 获取钱包流水数据
const loadTransactions = async (isLoadMore = false) => {
  if (loading.value) return;
  
  loading.value = true;
  
  try {
    const params = {
      pageNo: isLoadMore ? currentPage.value : 1,
      pageSize: 10
    };
    
    // 根据当前选中的标签设置isIncome参数
    if (activeTab.value === 1) {
      params.isIncome = 1; // 支出
    } else if (activeTab.value === 2) {
      params.isIncome = 0; // 收入
    }
    // activeTab为0时不设置isIncome，获取全部数据
    
    const data = await getWalletPage(params);
    const newData = data || [];
    
    if (isLoadMore) {
      // 分页加载，追加数据
      transactions.value = [...transactions.value, ...newData];
    } else {
      // 首次加载或切换标签，替换数据
      transactions.value = newData;
      currentPage.value = 1;
    }
    
    // 判断是否还有更多数据
    hasMore.value = newData.length === 10;
    
    if (hasMore.value) {
      currentPage.value++;
    }
    
  } catch (error) {
    console.error('获取钱包流水失败:', error);
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  
  const date = new Date(dateTime);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
};

// 格式化交易数据为按月分组的格式
const formatTransactions = (data) => {
  const grouped = {};
  
  data.forEach(item => {
    const date = new Date(item.createTime || item.time);
    const monthKey = `${date.getFullYear()}年${date.getMonth() + 1}月`;
    
    if (!grouped[monthKey]) {
      grouped[monthKey] = [];
    }
    
    grouped[monthKey].push({
      title: item.title || item.description || '交易记录',
      time: formatDateTime(item.createTime || item.time),
      amount: (item.amount || 0).toFixed(2),
      isIncome: item.isIncome === 0, // 0为收入，1为支出
      type: item.isIncome === 0 ? 'income' : 'expense',
      typeIcon: item.isIncome === 0 ? '收' : '支'
    });
  });
  
  // 转换为数组格式并按时间排序
  return Object.keys(grouped)
    .sort((a, b) => new Date(b) - new Date(a))
    .map(month => ({
      month,
      items: grouped[month].sort((a, b) => new Date(b.time) - new Date(a.time))
    }));
};

// 格式化后的交易数据
const filteredTransactions = computed(() => {
  return formatTransactions(transactions.value);
});

// 切换标签时重新加载数据
const handleTabChange = (tab) => {
  activeTab.value = tab;
  currentPage.value = 1;
  hasMore.value = true;
  loadTransactions(false);
};

const goBack = () => {
  uni.navigateBack();
};

// 页面加载时获取数据
onMounted(() => {
  loadTransactions();
});

// 上拉加载更多
onReachBottom(() => {
  // console.log('onReachBottom triggered', { hasMore: hasMore.value, loading: loading.value });
  if (hasMore.value && !loading.value) {
    // console.log('Loading more transactions...');
    loadTransactions(true);
  }
});
</script>

<style scoped>
.container {
  height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
}

.back-btn {
  font-size: 32rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
}

.placeholder {
  width: 60rpx;
}

.tabs {
  display: flex;
  justify-content: space-around;
  background-color: #fff;
  padding: 0 30rpx;
  border-bottom: 1rpx solid #eee;
}

.tab-item {
  position: relative;
  padding: 30rpx 0;
  font-size: 32rpx;
  flex: 1;
  text-align: center;
}

.tab-item.active {
  /*color: #1BCCB4;*/
  /*font-weight: bold;*/
}

.tab-line {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 150rpx;
  height: 6rpx;
  background-color: #1BCCB4;
  border-radius: 3rpx;
}

.transaction-list {
  padding-bottom: 40rpx;
}

.month-header {
  font-size: 25rpx;
  padding: 5rpx 30rpx 5rpx 30rpx; /* 修改：添加左右padding */
  background-color: #f5f5f5;
}

.transaction-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 0; /* 修改：移除底部margin */
  border-radius: 0; /* 修改：移除圆角 */
  position: relative; /* 添加：相对定位，用于绝对定位分割线 */
}

.transaction-item::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 20rpx; /* 设置左侧边距，与图标对齐 */
  right: 0;
  height: 1rpx;
  background-color: #E5E5E5;
}

/* 移除原来的边框样式 */
/* border-bottom: 1rpx solid #eee; */
/* } */

.transaction-left {
  display: flex;
  align-items: center;
}

.transaction-type-icon {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24rpx;
  color: #1BCCB4; /* 修改：文字颜色改为对应类型颜色 */
  margin-right: 20rpx;
  background-color: #fff; /* 修改：背景色改为白色 */
  border: 1rpx solid; /* 添加：边框 */
}

.transaction-type-icon.expense {
  color: #7D7D7D; /* 修改：支出类型文字颜色 */
  border-color: #1BCCB4; /* 添加：支出类型边框颜色 */
  background-color: #fff; /* 修改：背景色改为白色 */
  border-radius: 10rpx;
  font-size: medium;
  font-weight: 1000;
}

.transaction-type-icon.income {
  color: #7D7D7D; /* 修改：收入类型文字颜色 */
  border-color: #FF9500; /* 添加：收入类型边框颜色 */
  background-color: #fff; /* 修改：背景色改为白色 */
  border-radius: 10rpx;
  font-size: medium;
  font-weight: 1000;
}

.transaction-info {
  display: flex;
  flex-direction: column;
}

.transaction-title {
  font-size: 30rpx;
  margin-bottom: 10rpx;
}

.transaction-time {
  font-size: 24rpx;
  color: #999;
}

.transaction-amount {
  font-size: 32rpx;
}

.loading-tip {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
  font-size: 28rpx;
}
</style>